import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, PixelRatio, Image
} from "react-native";
import { GLOBAL } from '../../../../../config/global';
import { style } from '../../../../../theme/style';
import Dictionary from '../../../../../utils/dictionary'
import MethodUtil from '../../../../../utils/MethodUtil';
import { CURRENCY } from '../../../../../utils/helper';
import { ApproveRefuseModal } from '../../details/modals/refuse';
import OrderApproveService from '../../_common/service';
import ToastUtil from '../../../../../utils/toast';
const scale = GLOBAL.SCALE;
const arrowRight = require('../../../../../imgs/arrow-right-black.png');//背靠背
const unfold = require('../../../../../imgs/unfold.png');

export class OrderApproveItem extends Component {
	constructor(props) {
		super(props);

		this.state = {
			pageFlowMap: {},
			fold: true,
			refuseModalVisible: false,
			loaded: false
		}
	}

	componentWillMount() {
		this.initPageMap();
	}

	async initPageMap() {
		const pageFlowDict = await Dictionary.get('APP_PAGE_FLOW_ROLE_MAPPING');
		let map = {};
		pageFlowDict.forEach(item => {
			map[item.dictKey] = item.comments;
		});
		this.setState({
			pageFlowMap: map
		})
	}

	async _fetchApproval() {
		let { loaded } = this.state || {};
		const { itemInfo, approveType, choice, loadRefresh } = this.props;
		let { businessKey, taskId, formKey } = itemInfo;
		if (loaded) return;
		this.setState({ loaded: true });
		const responseData = await OrderApproveService.goApprove(
			{ approveType: approveType }, {
				businessKey: businessKey,
				taskId: taskId,
				formKey: formKey,
				auditResult: this.isAgreed,
				remark: this.remark, // 填写
				corpId: choice.corpId,
			});
		this.setState({ loaded: false, refuseModalVisible: false });
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => { loadRefresh() })
		}
	}

	goDetailFuc() {
		const { itemInfo, goDetail, approveType } = this.props;
		const { pageFlowMap } = this.state;
		let { businessKey, taskId, formKey, orderInfo,
			auditResultName } = itemInfo;
		if (!orderInfo) return;
		let orderType = orderInfo.orderType === 'S' ? '销售' : '采购';
		let orderTypeLabel = '';
		let title = '';
		if (orderInfo.periodType === 'L') {
			title = '长约' + orderType + '框架审批';
		} else {
			orderTypeLabel = orderInfo.longOrderId ? '长约' : (orderInfo.isFuture === 1 ? '远期' : (orderInfo.isAgency == 1 ? '代理' : (orderInfo.bizMode == 1 ? '闭口' : '现货')));
			title = orderTypeLabel + orderType + '成交报告审批';
		}

		goDetail({
			orderId: orderInfo.orderId ? orderInfo.orderId : '',
			businessKey,
			taskId,
			formKey,
			companyName: orderInfo.companyName ? orderInfo.companyName : '',
			taskType: pageFlowMap[formKey] || 'ApprovalDefaultPage',
			resUrl: 'OrderApprovePage',
			auditResultName,
			approveType
		}, title)
	}

	onFoldChange() {
		this.setState({
			fold: !this.state.fold
		})
	}
	approveAgree() {
		this.isAgreed = '1';
		this.remark = "";
		this.setState({
			refuseModalVisible: true
		})
	}

	approveRefuse() {
		this.isAgreed = '0';
		this.remark = "";
		this.setState({
			refuseModalVisible: true
		})
	}
	render() {
		const { itemInfo, goDetail, approveType, choice } = this.props;
		const { pageFlowMap, fold } = this.state;
		let { businessKey, taskId, taskName, formKey, orderInfo, resUrl, orderItemList,
			auditResultName, createTime } = itemInfo;
		let orderItemListSlice
		if (orderItemList && orderItemList.length > 2 && fold) {
			orderItemListSlice = orderItemList.slice(0, 2)
		}
		else {
			orderItemListSlice = orderItemList
		}

		return (
			<View style={styles.order}>
				<View>
					<View style={styles.orderHead}>
						<View style={styles.orderHeadLeft}>
							<Text style={styles.orderHeadText}>
								{
									orderInfo && orderInfo.companyName ? (
										orderInfo.companyName.length > 14 ? orderInfo.companyName.substr(0, 14) + '...' : orderInfo.companyName
									) : null
								}
							</Text>
						</View>
						<Text style={styles.statusText}>{createTime || '-'}</Text>
						{/* <Text style={styles.statusText}>{auditResultName}</Text> */}
					</View>
				</View>
				<TouchableOpacity key={taskId + businessKey} activeOpacity={.5} style={styles.orderCell}
					onPress={() => {
						this.goDetailFuc()
					}
					}>
					<View style={styles.orderHeadView}>
						<View>
							<View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 5 }}>
								<Text style={styles.ordertitle}>{orderInfo && orderInfo.orderId ? orderInfo.orderId : null}</Text>
								{orderInfo.bizMode != 1 && orderInfo.orderType === 'P' ?
									<View style={[styles.orderType, { backgroundColor: '#F7B500' }]}>
										<Text style={{ fontSize: 11, color: '#FFF' }}>采</Text>
									</View> : null
								}
								{orderInfo.bizMode != 1 && orderInfo.orderType === 'S' ?
									<View style={[styles.orderType, { backgroundColor: '#3E7406' }]}>
										<Text style={{ fontSize: 11, color: '#FFF' }}>销</Text>
									</View> : null
								}
								{orderInfo.sourceChannel === '2' ?
									<View style={[styles.orderType, { backgroundColor: '#E02020' }]}>
										<Text style={{ fontSize: 11, color: '#FFF' }}>壹化</Text>
									</View> : null
								}
								{orderInfo.bizMode == 1 ?
									<View style={[styles.orderType, { backgroundColor: '#E02020' }]}>
										<Text style={{ fontSize: 11, color: '#FFF' }}>闭</Text>
									</View> : null
								}
							</View>
							<Text style={{ fontSize: 10 * scale, color: '#848A96' }}>
								业务组织：{choice.corpName || '-'} | 业务员：
								{orderInfo && orderInfo.bizStaffName ? orderInfo.bizStaffName + ' | ' : '--'}
								{orderInfo && orderInfo.bizTeamName ? orderInfo.bizTeamName + ' | ' : '--'}
								{orderInfo && orderInfo.bizOrganName ? orderInfo.bizOrganName : '--'}
							</Text>
						</View>
						<Image source={arrowRight} style={styles.arrow} />
					</View>
					<View style={styles.costTableLine}></View>
					<View style={styles.orderMain}>
						{
							orderItemListSlice && orderItemListSlice.length > 0 ?
								orderItemListSlice.map((orderItemListSlice, index) => {
									return (
										<View key={index} style={{ marginBottom: 15 }}>
											<View style={styles.orderCol}>
												<View>
													<Text style={styles.orderValTitle}>{orderItemListSlice.goodsName.length > 14 ? orderItemListSlice.goodsName.substr(0, 14) + '...' : orderItemListSlice.goodsName || null}</Text>
												</View>
												<View style={{ flexDirection: "row", alignItems: 'center' }}>
													<Text style={[styles.priceType, orderItemListSlice.priceType == 2 ? { color: '#FA6400', backgroundColor: '#FBEFE8' } : { color: '#85C0EC', backgroundColor: '#ECF7FF' }]}>
														{orderItemListSlice.priceType == 2 ? '暂定价' : '一口价'}
													</Text>
													<Text style={styles.orderVal}>
														¥ {MethodUtil.toThousands(orderItemListSlice.price || 0, 2)}元/{orderItemListSlice.uomName ? orderItemListSlice.uomName : '吨'}
													</Text>
												</View>
											</View>
											<View style={{ alignItems: 'flex-end' }}>
												<Text style={{ fontSize: 12, color: '#8D8D8D' }}>
													数量 ：
													{orderItemListSlice.quantity ? orderItemListSlice.quantity : 0}
													{orderItemListSlice.uomName ? orderItemListSlice.uomName : '吨'}
												</Text>
											</View>
										</View>
									)
								})
								: null
						}
					</View>

					{orderItemList && orderItemList.length > 2 ?
						<TouchableOpacity style={{ alignItems: 'center', paddingTop: 5, paddingBottom: 10 }} onPress={() => { this.onFoldChange() }}>
							<View>
								<Image source={unfold} style={fold ? styles.fold : styles.unfold} />
							</View>
						</TouchableOpacity>
						: null
					}
					<View style={styles.costTableLine}></View>
					<View style={styles.bottomTotol}>
						<View>
							<Text style={{ fontSize: 11 }}>
								共{orderInfo.totalOrderQuantity ? orderInfo.totalOrderQuantity : 0}
								{orderInfo.uomName ? orderInfo.uomName : '吨'},
								合计：{CURRENCY.getUnit(orderInfo.currency).label + MethodUtil.toThousands(orderInfo.totalOrderAmt || 0, 2) + CURRENCY.getUnit(orderInfo.currency).text}
							</Text>
						</View>
						<View style={styles.bottomTotolRight}>
							<TouchableOpacity style={styles.bottomButtonLeft} onPress={() => { this.approveAgree(); }}>
								<Text style={{ fontSize: 12, color: "#fff" }}>同意</Text>
							</TouchableOpacity>
							<TouchableOpacity style={styles.bottomButtonRight} onPress={() => { this.approveRefuse(); }}>
								<Text style={{ fontSize: 12, color: "#0E7FFD" }}>驳回</Text>
							</TouchableOpacity>
						</View>
					</View>
				</TouchableOpacity>
				<ApproveRefuseModal
					auditRemark={this.remark}
					visible={this.state.refuseModalVisible}
					titleText={'审批意见'}
					placeholderText={this.isAgreed == '1' ? '请输入同意原因' : null}
					propDefaultValue={this.isAgreed == '1' ? '审批同意' : '审批驳回'}
					btnPress={(remark) => {
						this.remark = remark;
						if (!this.remark && OrderApproveService.TASK_KEY[this.taskType] === 'L' && this.isAgreed == '0') {
							this.setState({
								refuseModalVisible: false,
							});
							ToastUtil.showWarning('请输入驳回原因');
							return;
						} else {
							this._fetchApproval();
						}
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
			</View>
		)
	}
}

const styles = StyleSheet.create({
	orderCell: {
		// width: 375 * scale,
		backgroundColor: '#fff',
		// alignItems: 'center',
		marginBottom: 12,
		borderRadius: 6,
		paddingTop: 6,
		// paddingBottom: 10
	},
	order: {
		// backgroundColor: '#e4e4e4'
		// width: 351 * scale,
	},
	orderHead: {
		// width: 351 * scale,
		height: 44 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderHeadView: {
		paddingLeft: 14,
		paddingRight: 14,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingBottom: 10,
		// borderBottomColor: '#e4e4e4',
		// borderBottomWidth: 1,
	},
	costTableLine: {
		borderBottomWidth: 1 / PixelRatio.get(),
		backgroundColor: '#E3E7F0',
		borderStyle: 'solid',
		opacity: 0.3,
	},
	orderHeadLeft: {
		height: 44 * scale,
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderHeadText: {
		fontSize: 14 * scale,
		color: '#222',
		// marginRight: 6 * scale,
		// marginLeft: 6 * scale,
		flexWrap: 'wrap',
	},
	conImage: {
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
	},
	forwardText: {
		paddingTop: 2 * scale,
		marginTop: 2 * scale,
		marginRight: 6 * scale,
		width: 30 * scale,
		height: 16 * scale,
		backgroundColor: '#49CAFF',
		color: '#FFFFFF',
		fontSize: 11 * scale,
		textAlign: 'center',
		borderRadius: 4 * scale,
	},
	statusText: {
		fontSize: 12 * scale,
		color: '#848A96',
	},
	orderCol: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingBottom: 10,
	},
	orderText: {
		fontSize: 12 * scale,
		color: '#8B8B8B'
	},
	orderVal: {
		fontSize: 12 * scale,
		color: '#000'
	},
	orderMain: {
		paddingTop: 8 * scale,
		// paddingBottom: 8 * scale,
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
	},
	tip: {
		color: '#fff',
		fontSize: 12 * scale,
		borderRadius: 4 * scale,
		paddingRight: 5 * scale,
		paddingLeft: 5 * scale,
		marginRight: 5 * scale
	},
	ordertitle: {
		fontSize: 12 * scale,
	},
	arrow: {
		width: 6,
		height: 8
	},
	orderValTitle: {
		fontSize: 13,
		color: '#0C0C0D',
		fontWeight: '600'
	},
	bottomTotol: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		paddingHorizontal: 12,
		paddingVertical: 15,
		alignItems: 'center',
	},
	bottomTotolRight: {
		flexDirection: 'row',
		justifyContent: 'space-between',

	},
	bottomButtonLeft: {
		backgroundColor: '#0E7FFD',
		borderWidth: 1,
		borderColor: '#0E7FFD',
		borderRadius: 30,
		paddingHorizontal: 24,
		paddingVertical: 7,
		marginRight: 9
	},
	bottomButtonRight: {
		borderWidth: 1,
		borderColor: '#0E7FFD',
		borderRadius: 30,
		paddingHorizontal: 24,
		paddingVertical: 7,
	},
	fold: {
		marginTop: 5,
		height: 15,
		width: 15
	},
	unfold: {
		marginTop: 5,
		height: 15,
		width: 15,
		transform: [{ rotate: '180deg' }]
	},
	orderType: {
		borderRadius: 2,
		paddingHorizontal: 4,
		paddingVertical: 2,
		marginLeft: 5
	},
	priceType: {
		backgroundColor: '#FBEFE8',
		borderRadius: 2,
		paddingVertical: 2,
		paddingHorizontal: 5,
		fontSize: 11,
		color: '#FA6400',
		marginRight: 5
	}
})